package com.devilvan.controller;


import com.devilvan.entity.Dept;
import com.devilvan.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2020-11-10
 */
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    // 可以获取微服务的具体信息
    @Autowired
    private DiscoveryClient client;

    @GetMapping("addDept")
    public boolean addDept(Dept dept) {
        return deptService.addDept(dept);
    }

    @GetMapping("queryDeptById/{dept_id}")
    public Dept queryDeptById(@PathVariable("dept_id") Long dept_id) {
        return deptService.queryDeptById(dept_id);
    }

    @GetMapping("queryAllDepts")
    public List<Dept> queryAllDepts() {
        return deptService.queryAllDepts();
    }

    // 通过au，获取服务列表
    @GetMapping("discovery")
    public Object discovery() {
        List<String> services = client.getServices();
        System.out.println("services: " + services);

        // 获取Instances 时的服务ID，对应yml里的instance-id
        List<ServiceInstance> instances = client.getInstances("8003-provider");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    "Host:" + instance.getHost() + "\t" +
                    "Port:" + instance.getPort() + "\t" +
                    "Instance-Id:" + instance.getInstanceId() + "\t" +
                    "Service-Id:" + instance.getServiceId()
            );
        }
        return this.client;
    }
}
